package com.stars.easyms.swagger.autoconfigure;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.stars.easyms.base.constant.CommonConstants;
import com.stars.easyms.base.util.SpringBootUtil;
import com.stars.easyms.monitor.handler.EasyMsRequestMappingHandlerMapping;
import com.stars.easyms.swagger.handler.EasyMsSwaggerRequestHandler;
import com.stars.easyms.swagger.properties.EasyMsSwaggerProperties;
import com.stars.easyms.base.util.BeanUtil;
import com.stars.easyms.base.util.PropertyPlaceholderUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger自动配置类
 *
 * @author guoguifang
 * @date 2018-04-23 13:54
 * @since 1.0.0
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(EasyMsSwaggerProperties.class)
@ConditionalOnProperty(prefix = EasyMsSwaggerProperties.SWAGGER_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class EasyMsSwaggerAutoConfiguration {

    private ConfigurableApplicationContext applicationContext;

    private EasyMsSwaggerProperties easyMsSwaggerProperties;

    public EasyMsSwaggerAutoConfiguration(ConfigurableApplicationContext applicationContext, EasyMsSwaggerProperties easyMsSwaggerProperties) {
        this.applicationContext = applicationContext;
        this.easyMsSwaggerProperties = easyMsSwaggerProperties;
        EasyMsRequestMappingHandlerMapping easyMsSwaggerHandlerMapping = new EasyMsRequestMappingHandlerMapping(applicationContext);
        easyMsSwaggerHandlerMapping.detectHandlerMethods(new EasyMsSwaggerRequestHandler(easyMsSwaggerProperties));
        BeanUtil.registerSingleton(applicationContext, "easyMsSwaggerHandlerMapping", easyMsSwaggerHandlerMapping);
    }

    @Bean
    public Docket createRestApi() {
        ApiSelectorBuilder bulider = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select();
        String basePackage = easyMsSwaggerProperties.getBasePackage();
        if (!StringUtils.hasText(basePackage)) {
            String springApplicationPackageName = SpringBootUtil.getSpringApplicationPackageName();
            if (springApplicationPackageName != null) {
                basePackage = springApplicationPackageName;
            }
        }
        return bulider.apis(basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(applicationContext.getId() + " RESTful APIs")
                .description(PropertyPlaceholderUtil.replace("spring.application.description", ""))
                .version("1.0")
                .build();
    }

    private static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            if (input != null) {
                for (String strPackage : StringUtils.tokenizeToStringArray(basePackage, CommonConstants.PROPERTIES_SEPARATOR)) {
                    Package packagei = input.getPackage();
                    if (packagei != null) {
                        boolean isMatch = packagei.getName().startsWith(strPackage);
                        if (isMatch) {
                            return true;
                        }
                    }
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
